// 1. 启动一个后端服务
const express = require('express');
const exApp = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const cheerio = require('cheerio');
const http = require('http');
const https = require('https');
const fs = require('fs');
const Nightmare = require('nightmare');          // 自动化测试包，处理动态页面
const nightmare = Nightmare({ show: false });     // show:true  显示内置模拟浏览器
// 1.2 配置post请求
exApp.use(bodyParser.urlencoded({ extended: true }));
exApp.use(bodyParser.json());
// 1.3 开启跨域设置
exApp.use(cors());
// 1.4 开启后端服务端口
exApp.listen(3000, () => console.log(`后台服务启动成功::::::http://localhost:3000`));

// 查找图片方法
let getLocalNews = (htmlStr) => {
  let localNews = [];
  let $ = cheerio.load(htmlStr);

  $('li>a>span>image').each((idx, ele) => {
    let href = $(ele).attr('src')
    localNews.push('http://pic.netbian.com/' + href);
  });
  return localNews
}

exApp.get('/', async function (req, res) {
  let localNews = await nightmare
    .goto('http://pic.netbian.com/')
    .wait(".clearfix")
    .evaluate(() => document.querySelector(".clearfix").innerHTML)
    .then(htmlStr => {
      return getLocalNews(htmlStr)
    })
    .catch(error => {
      console.log(`抓取内容失败 - ${error}`);
    })
  for (let index = 0; index < localNews.length; index++) {
    saveImage(localNews[index])
  }
});

// 保存图片的方法
function saveImage (imageUrl) {
  https.get(imageUrl, function (res) {
    res.setEncoding('binary'); //二进制(binary)
    var imageData = '';
    res.on('data', function (data) { //图片加载到内存变量
      imageData += data;
    }).on('end', async function () { //加载完毕保存图片
      if (!fs.existsSync("./images")) {
        fs.mkdirSync("./images");
      }
      await fs.writeFile('images/' + Math.floor(Math.random() * 10000000) + '.png', imageData, 'binary', function (err) { //以二进制格式保存
        if (err) throw err;
        console.log('保存成功');
      });
    });
  });
}